#include "ZipCompressor.h"
#include "FileUtils.h"
#include "PathBuilder.h"

ZipCompressor::ZipCompressor()
{
    this->builder_ = new ZipBuilder();
    this->writer_ = new ZipWriter();
}

ZipCompressor::~ZipCompressor()
{
    if(this->builder_)
        delete this->builder_;
    if(this->writer_)
        delete this->writer_;
}

void ZipCompressor::loadFileToCompress(std::vector<std::string> pathsList, std::vector<FilePathData>& filesToCompress)
{
    for(std::vector<std::string>::iterator it = pathsList.begin(); it != pathsList.end(); it++)
    {
        std::string actualPath =(*it);
        if(isDirectory(actualPath.c_str())){
           actualPath = appendSlash(actualPath.c_str());            
        }
        std::string pathBuilder = backToRelativePath(actualPath);
        PathBuilder builder(pathBuilder);
        builder.buildPaths(actualPath, filesToCompress);
    }
}

void ZipCompressor::compress(std::vector<std::string> pathsList, const char* destinyPath, const char* fileName)
{
    std::vector<FilePathData> fileToCompress;
    loadFileToCompress(pathsList, fileToCompress);
    int vectorSize = fileToCompress.size();
    std::vector<FileHeader*> fileHeaders = this->builder_->assembleCompressedZipFile(fileToCompress);
    EndOfCentralDirectory* endOfCentralDirectory = this->builder_->endOfCentralDirectory_;
    this->writer_->write(fileHeaders, endOfCentralDirectory, destinyPath, fileName);

    for(std::vector<FileHeader*>::iterator fileHeaderIt = fileHeaders.begin();
            fileHeaderIt != fileHeaders.end(); fileHeaderIt++)
    {
        FileHeader* fileHeader = *fileHeaderIt;
        CentralDirectory* centralDirectory = fileHeader->centralDirectory_;
        delete centralDirectory;
        fileHeader->centralDirectory_ = 0;

        delete fileHeader;
    }

    fileHeaders.clear();
    delete endOfCentralDirectory;
}
